package com.six.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.six.core.util.JwtUtil;
import com.six.core.util.WebUtil;
import com.six.core.vo.Result;
import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author: WangPeng
 * @createTime: 2023/02/27 11:35
 * @description:
 * @version: v1.0
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象request和相应对象response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getPath().toString();
        //如果请求路径为login放行
        if ("/login".equals(path)
                || "/firstpage/api/banner/getAllBanner".equals(path)
                || "/firstpage/api/zone/getAllZone".equals(path)
                || "/firstpage/api/link/getAllLink".equals(path)
                || "/firstpage/api/link/getAllLinkArticle".equals(path)
                || "/firstpage/api/notice/getAllNotice".equals(path)
                ||  "/firstpage/api/headnav/getAllHeadNav".equals(path)
                ||  "/firstpage/api/bottomArticle/getAllBottomArticle".equals(path)
                || "/firstpage/api/link/getAllLink".equals(path)
                || path.startsWith("/firstpage/api/aritcle/getArticleByNavId/")
                || "/firstpage/api/headnav/getAllHeadNav".equals(path)
                || "/qianlogin".equals(path)
                || "/firstpage/api/notice/getNotice".equals(path)
                || path.startsWith("/goods/goods/selectBycategoryid")
                || path.startsWith("/business/business/getIsType")
                || path.startsWith("/goods/goods/selectGoodsByid/")
                || path.startsWith("/goods/category/selecg")
                || path.startsWith("/emp/emp/updatePassword")
                || path.startsWith("/user/user/send")
                || path.startsWith("/user/user/addUser")
                || path.startsWith("/remark/api/remark/findAll")
                || path.startsWith("/goods/goods/selectBycategory")
        ){
            //System.out.println("path = " + path);
            return chain.filter(exchange);
        }
        //获取请求头
        String token = request.getHeaders().getFirst("token");

        System.out.println(token);
        System.out.println("JwtUtil.verifyToken:"+JwtUtil.verifyToken(token));
        System.out.println("redisTemplate.hasKey:"+redisTemplate.hasKey(token));

        //判断并解析token
        if (StringUtils.hasText(token) && JwtUtil.verifyToken(token) && redisTemplate.hasKey(token)){
            //刷新token时间
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
            //放行
            return chain.filter(exchange);
        }
        Result result = new Result(501,"登录失效,请先登录");
        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }
    @Override
    public int getOrder() {
        return 0;
    }

    public static void main(String[] args) {
        boolean b = JwtUtil.verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJlbXBJZCI6NCwiYXV0aG9yaXRpZXMiOltdLCJ1c2VybmFtZSI6ImFkbWluIn0sImlzcyI6IndhbmdwZW5nIiwiZXhwIjoxNjc4NDYwNDM5LCJpYXQiOjE2Nzg0NTMyMzl9.t2XnPJzHUAk2GBaym7JELaHRzJfvV3_66d78T0sTRoo");
        System.out.println("b = " + b);
    }
}
